package com.vj.analyzeFakeNames;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import junit.framework.Assert;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.junit.Test;

//SolrDocument doc = docs.get(i);
//System.out.println("\t"+doc.toString());
// it's good
public class Queryer {
	
	SolrServer server = new HttpSolrServer("http://192.168.71.145:8080/solr");
	


	///////////////////////////////////////////////////////////////////
	@Test public void valid_have_5_indexes() throws SolrServerException{
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ valid_have_5_indexes");
		SolrQuery q = new SolrQuery("*:*");
		QueryResponse rsp = server.query(q);
		
		Assert.assertEquals( 5 , rsp.getResults().getNumFound());
	}


	///////////////////////////////////////////////////////////////////
	@Test public void queryAll_by_Road() throws SolrServerException {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryAll_by_Road");
		//use CopyField
		SolrQuery q = new SolrQuery("fn_collector:Road");
		QueryResponse rsp = server.query(q);
		print(rsp);
		long numFound = rsp.getResults().getNumFound();
		Assert.assertTrue( 0 < numFound);
		Assert.assertEquals(0, numFound);
	}


	///////////////////////////////////////////////////////////////////
	@Test public void queryAll_by_Old() throws SolrServerException {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryAll_by_Old");
		//use CopyField
		SolrQuery q = new SolrQuery("fn_collector:Old");
		QueryResponse rsp = server.query(q);
		print(rsp);
		long numFound = rsp.getResults().getNumFound();
		Assert.assertTrue( 0 < numFound);
		Assert.assertEquals(3, numFound);
	}


	///////////////////////////////////////////////////////////////////
	@Test public void filterQueryTest() {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ filterQueryTest");
//		fq – （filter query）过虑查询，作用：在q查询符合结果中同时是fq查询符合的，
//		例如：q=mm&fq=date_time:[20081001 TO 20091031]，找关键字mm，
//		并且date_time是20081001到20091031之间的。
//		官方文档：http://wiki.apache.org/solr/CommonQueryParameters
			
		Assert.assertTrue(false);
	}
	


	///////////////////////////////////////////////////////////////////
	@Test public void readMaterial (){
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ readMaterial");
		/*
[Solr的检索运算符]
20	“:” 指定字段查指定值，如返回所有值*:*²
21	“?”²表示单个任意字符的通配
22	“*” 表示多个任意字符的通配（不能在检索的项开始使用*或者?符号）²
23	“~”²表示模糊检索，如检索拼写类似于”roam”的项这样写：roam~将找到形如foam和roams的单词；roam~0.8，检索返回相似度在0.8以上的记录。
24	²邻近检索，如检索相隔10个单词的”apache”和”jakarta”，”jakarta apache”~10
25	“^”²控制相关度检索，如检索jakarta apache，同时希望去让”jakarta”的相关度更加好，那么在其后加上”^”符号和增量值，即jakarta^4 apache
26	布尔操作符AND、||²
27	布尔操作符OR、²&&
28	布尔操作符NOT、!、-²（排除操作符不能单独与项使用构成查询）
29	“+” 存在操作符，要求符号”+”后的项必须在文档相应的域中存在²
30	( ) 用于构成子查询²
31	² [] 包含范围检索，如检索某时间段记录，包含头尾，date:[200707 TO 200710]
32	{}²不包含范围检索，如检索某时间段记录，不包含头尾
33	date:{200707 TO 200710}
34	” 转义操作符，特殊字符包括+ – & | ! ( ) { } [ ] ^ ” ~ * ? : “ 
		 */
		
		Assert.assertTrue(false);
	}


	///////////////////////////////////////////////////////////////////
	@Test
	public void filterQueryTest002() throws SolrServerException {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ filterQueryTest002");

		SolrQuery query = new SolrQuery();

		// 主查询

		query.setQuery("*:*");

		// 采用过滤器查询可以提高性能

		query.addFilterQuery("Searchable:1");

		query.addFilterQuery("SpaceAccessPrivate:1");

		// 区间查询

		query.addFilterQuery("Age:[* TO 50]");

		query.addFilterQuery("FriendType:1");

		// 添加排序

		query.addSortField("Score", ORDER.desc);

		Assert.assertTrue(false);
	}


	///////////////////////////////////////////////////////////////////
	/**
	 * Print documents and facets
	 * @param response
	 */
	public static void print(QueryResponse response) {
		SolrDocumentList docs = response.getResults();
		if(docs!=null){
			System.out.println(docs.getNumFound()+" documents found, " +docs.size()+" returned : ");
			for(int i=0;i<docs.size();i++){
				SolrDocument doc = docs.get(i);
				System.out.println("\t"+doc.toString());
			}
		}
		
		List<FacetField> fieldFacets = response.getFacetFields(); //TODO deep meaning
		if(fieldFacets!=null && !fieldFacets.isEmpty()){
			System.out.println("\nField Facets : ");
			for(FacetField fieldFacet:fieldFacets){
				System.out.println("\t"+fieldFacet.getName()+" :\t");
				if(fieldFacet.getValueCount()>0){
					for(Count count:fieldFacet.getValues()){
						System.out.println(count.getName()+" ["+count.getCount()+"]\t");
					}
				}
				System.out.println();
			}
		}
		
		NamedList<NamedList<Object>> spellCheckResponse = (NamedList<NamedList<Object>>) response.getResponse().get("spellcheck");
		
		if(spellCheckResponse !=null){
			Iterator<Entry<String, NamedList<Object>>> wordsIterator = spellCheckResponse.iterator();
			
			while(wordsIterator.hasNext()){
				Entry<String, NamedList<Object>> entry = wordsIterator.next();
				String word = entry.getKey();
				NamedList<Object> spellCheckWordResponse = entry.getValue();
				boolean correct = spellCheckWordResponse.get("frequency").equals(1);
				System.out.println("Word: "+word+",\tCorrect?: "+correct);
				NamedList<Integer> suggestions = (NamedList<Integer>)spellCheckWordResponse.get("suggestions");
				if(suggestions!=null && suggestions.size()>0){
					System.out.println("Suggestions : ");
					Iterator<Entry<String, Integer>> suggestionsIterator = suggestions.iterator();
					while(suggestionsIterator.hasNext()){
						System.out.println("\t"+suggestionsIterator.next().getKey());
					}
				}
				System.out.println();
			}
		}
		
	}
	


	///////////////////////////////////////////////////////////////////
	@Test public void queryAll_by_Road_pre_wildcard() throws SolrServerException {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryAll_by_Road_pre_wildcard");
		//use CopyField
		SolrQuery q = new SolrQuery();
//		q.setQuery("fn_collector:Road");
		q.setQuery("fn_collector:*oad");// or %oad, ?oad ; take a try
		QueryResponse rsp = server.query(q);
		print(rsp);
		long numFound = rsp.getResults().getNumFound();
		Assert.assertTrue( 0 < numFound);
		Assert.assertEquals(0, numFound);
	}
	


	///////////////////////////////////////////////////////////////////
	@Test public void queryAll_by_Road_post_wildcard() throws SolrServerException {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryAll_by_Road_post_wildcard");
		//use CopyField
		SolrQuery q = new SolrQuery();
//		q.setQuery("fn_collector:Road");
		q.setQuery("fn_collector:Ro*");
		QueryResponse rsp = server.query(q);
		print(rsp);
		long numFound = rsp.getResults().getNumFound();
		Assert.assertTrue( 0 < numFound);
		Assert.assertEquals(0, numFound);
	}


	///////////////////////////////////////////////////////////////////
	@Test public void queryAll_by_Green() throws SolrServerException {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryAll_by_Green");
		//use CopyField
		SolrQuery q = new SolrQuery();
		q.setQuery("fn_collector:Green*");
		QueryResponse rsp = server.query(q);
		print(rsp);
		long numFound = rsp.getResults().getNumFound();
		Assert.assertTrue( 0 < numFound);
		Assert.assertEquals(0, numFound);
	}

	///////////////////////////////////////////////////////////////////
	

	@Test public void queryAll_by_Green_highlight() throws SolrServerException {
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryAll_by_Green_highlight");
		//use CopyField
		SolrQuery q = new SolrQuery();
		q.setQuery("fn_collector:Green*");
		q.setHighlight(true);
		q.set("hl.fl", "fn_username");
		
		QueryResponse rsp = server.query(q);
		print(rsp);
		long numFound = rsp.getResults().getNumFound();
		Assert.assertTrue( 0 < numFound);
		
		System.out.println("printing Highlighting:");
		Map<String, Map<String, List<String>>> highlighting = rsp.getHighlighting();
		SolrDocumentList docs = rsp.getResults();
		for(SolrDocument doc : docs){
			String id = (String) doc.get("id");
			Map<String, List<String>> idMap = highlighting.get(id);
			if(null != idMap) {
				List<String> highlightSnippets = idMap.get("fn_username");
//				Assert.assertTrue(highlightSnippets != null);
				System.out.println(highlightSnippets);
			}
			
		}

		
		Assert.assertEquals(0, numFound);
	}

	///////////////////////////////////////////////////////////////////
	@Test public void queryBy2Words_1() throws SolrServerException{
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryBy2Words_1:");
		SolrQuery query = new SolrQuery();
		query.setQuery("fn_address:austin ends ");
		QueryResponse rsp = server.query(query);
		print(rsp);
		
		Assert.assertTrue(rsp.getResults().size() == 3);// a,b,d txt
	}
	
	/////////////////////////////////////////////////////////////////
	@Test public void queryBy2Words_2() throws SolrServerException{
		System.out.println("\n\n>>>>>>>>>>>>>>>> @ queryBy2Words_2:");
		SolrQuery query = new SolrQuery();
		query.setQuery("fn_address:ends OR fn_address: austin  ");
		QueryResponse rsp = server.query(query);
		print(rsp);
		
		Assert.assertTrue(rsp.getResults().size() == 3);// a,b,d txt
	}
	
	
}
  